package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-27 14:50
 **/
@Service
public class MessageService {


    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /*添加联系人
    * //1.记录到探花数据库
        //2.好友记录到环信
    *
    *
    * */
    public void contacts(Long friendId) {
        Long userId = UserHolder.getUserId();
        //1.记录到探花数据库
        friendApi.save(userId,friendId);
        //2.好友记录到环信
        huanXinTemplate.addContact("hx"+userId,"hx"+friendId);
    }

    //查询联系人
    public PageResult findContacts(Integer page, Integer pagesize) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.调用API查询联系人 ---List<Friend>
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        //3.判断列表是否为空
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }

        //提取所有的好友id
        List<Long> friendIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //一次性查询所有的好友信息，构建map
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds);
        //4.一个friend构造一个vo
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //查询好友的用户信息UserInfo
            //获取好友id
            Long friendId = friend.getFriendId();
            UserInfo userInfo = map.get(friendId);
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        // 5.返回
        return new PageResult(page,pagesize,0l,vos);
    }
    //为了解决聊天页面头像和昵称不匹配问题
    public UserInfoVo findById(String huanxinId) {
        String id = huanxinId.substring(2);
        long userId = Long.parseLong(id);
        UserInfo userInfo = userInfoApi.findUser(userId);
        UserInfoVo userInfoVo = UserInfoVo.init(userInfo);
        return userInfoVo;
    }


    //解除环信
    public void deleteFriend(Long userId ,Long likeUserId) {
        huanXinTemplate.deleteContact("hx" + userId ,"hx" + likeUserId);
        friendApi.delete(userId ,likeUserId);
    }
}
